package com.tutu.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;


/**
 * @Program: Spring_New
 * @Description: Bean工厂后处理器，能够动态注册BeanDefinition,动态修改BeanDefinition,以及动态修改Bean的作用
 * BeanFactoryPostProcessor，bean工厂后处理器,在BeanDefinitionMap填充完毕，bean实例化之前执行
 * BeanDefinitionRegistryPostProcessor继承了BeanFactoryPostProcessor
 * @Author: JK.TuTu
 * @Version: 1.0
 * @Create: 2022-11-25 11:36
 **/
public class MyBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    /**
     * 父类BeanFactoryPostProcessor的方法
     * @param beanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("BeanDefinitionMap填充完毕后回调的方法");
        //注册BeanDefinition
      /*  BeanDefinition beanDefinition = new RootBeanDefinition();
        //设置要实例化bean的全限定路径
        beanDefinition.setBeanClassName("com.tutu.entity.Dog");
        //需要强制转换成DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
        defaultListableBeanFactory.registerBeanDefinition("dog",beanDefinition);*/
    }

    /**
     * 子类BeanDefinitionRegistryPostProcessor的方法
     * @param beanDefinitionRegistry
     * @throws BeansException
     */   @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        BeanDefinition  beanDefinition = (BeanDefinition)new RootBeanDefinition();
        //设置要实例化bean的全限定路径
        beanDefinition.setBeanClassName("com.tutu.entity.Dog");
        //设置bean实例的初始化方法
        beanDefinition.setInitMethodName("init");
        beanDefinitionRegistry.registerBeanDefinition("dog",beanDefinition);
    }
}
